package org.nViron.nvOrganism;

/**
 * Represents the states a organism can be in
 * @author Roland Haring <p>
 * <script type="text/javascript" src="http://www.ohloh.net/p/376434/widgets/project_basic_stats.js"></script>
 */
public class nvStateMgr {
    public static final int    DEAD         = 4;
    public static final int    DEGENERATING = 3;
    public static final int    INVALID      = -1;
    public static final int    LIVING       = 2;
    public static final int    SPAWN        = 0;
    public static final int    SPROUTING    = 1;
    private static final int[] stateCount   = new int[5];
    public static final int getCount(int state) {
        int ret = 0;

        synchronized (stateCount) {
            ret = stateCount[state];
        }

        return ret;
    }
    public static final String getIdentifier(int state) {
        switch (state) {
        case SPAWN :
            return "spawn";

        case SPROUTING :
            return "sprouting";

        case LIVING :
            return "living";

        case DEGENERATING :
            return "degenerating";

        case DEAD :
            return "dead";
        }

        return "invalid state";
    }

    private long               changeStamp;

    private int                state;

    public nvStateMgr() {
        state = INVALID;
        setState(SPAWN);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        setState(INVALID);
    }

    public final long getMsInState() {
        return System.currentTimeMillis() - changeStamp;
    }

    public final int getState() {
        return state;
    }

    public final boolean setState(int state) {
        if (state != this.state) {
            if (this.state == DEAD) {

                // throw new IllegalAccessError("A dead organism can not be respawn anymore!");
                // System.out.println("Warning: A dead organism can not be respawn anymore!");
                // return false;
            }

            if (state == SPAWN) {
                int i = 0;
            }

            if (this.state != INVALID) {
                synchronized (stateCount) {
                    stateCount[this.state]--;
                }
            }

            this.state = state;

            if (this.state != INVALID) {
                synchronized (stateCount) {
                    stateCount[this.state]++;
                }
            }

            changeStamp = System.currentTimeMillis();

            return true;
        }

        return false;
    }
}



